package com.qianyu.project.web.controller.lyz;

import com.qianyu.project.entity.MaterialNeed;
import com.qianyu.project.entity.MaterialNeedDetail;
import com.qianyu.project.service.IMaterialNeedService;
import com.qianyu.project.utils.Result;
import com.qianyu.project.utils.ResultTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author lyz
 * @date create in 2021/2/6 15:16
 */
@RestController
@RequestMapping("/MaterialNeed")
public class MaterialNeedController {
    @Autowired
    private IMaterialNeedService service;

    @GetMapping("")
    public Result getMaterialNeedList(@RequestParam Map<String,String> args){
        return ResultTool.success(service.getMaterialNeedList(args));
    }

    @PostMapping("")
    @Transactional
    public Result saveMaterialNeed(@RequestBody Map<String,Object> map){
        System.out.println(map);

        Map<String,Object> needMap= (Map<String, Object>) map.get("need");
        List<Map<String,Object>> needDetailsList= (List<Map<String, Object>>) map.get("needDetails");

        MaterialNeed need=new MaterialNeed();
        need.setPlanId(Integer.parseInt(needMap.get("planId").toString()));
        need.setFlowId(1);
        need.setApplyer(needMap.get("applyer").toString());
        need.setDate(needMap.get("date").toString());
        need.setNeedSubject(needMap.get("needSubject").toString());
        need.setComment(needMap.get("comment").toString());
        need.setApproveStatus(1);

        List<MaterialNeedDetail> details=new ArrayList<MaterialNeedDetail>();
        needDetailsList.forEach(d->{
            MaterialNeedDetail detail=new MaterialNeedDetail();
            detail.setMateId(Integer.parseInt(d.get("mateTypeId").toString()));
            detail.setUseCount(Long.parseLong(d.get("useCount").toString()));
            detail.setReferencePrice(new BigDecimal(d.get("price").toString()).multiply(new BigDecimal(detail.getUseCount())));
            detail.setUseTo(d.get("useTo").toString());
            detail.setComment(d.get("comment").toString());
            details.add(detail);
        });

        System.out.println(need);
        System.out.println(details);
        service.saveMaterialNeed(need,details);
        return ResultTool.success();
    }

    @GetMapping("/{id}")
    public Result getNeedById(@PathVariable String id){
        MaterialNeed need=service.getNeedById(id);
        return ResultTool.success(need);
    }

    @DeleteMapping("/{id}")
    public Result deleteNeed(@PathVariable String id){
        service.removeById(id);
        return ResultTool.success();
    }
}
